<template>
    <card dis-hover>
        <i-form inline :label-width="40" class="search-column">
            <form-item label="名称">
                <i-input v-model="search.title" clearable placeholder="请输入"/>
            </form-item>
            <form-item label="栏目">
                <tag-select :is-first="false" v-model="tag"/>
            </form-item>
            <form-item :label-width="0">
                <i-button :loading="loading" type="primary" icon="ios-search" @click="handlerSearch">搜索</i-button>
                <i-button type="success" icon="md-add" to="/article_ce">新增</i-button>
                <i-button type="error" @click="removeSelectsFn" v-show="selects.length > 0" icon="ios-trash">删除
                </i-button>
            </form-item>
        </i-form>
        <i-table stripe
                 border
                 :loading="loading"
                 :columns="table.header"
                 :data="table.body" @on-selection-change="selectTableFn"
                 @on-sort-change="sortFn"></i-table>
        <page class="pager"
              show-sizer
              :current="page.page"
              :total="page.total"
              @on-change="pageFn"
              @on-page-size-change="pageSizeChangeFn"
              prev-text="上一页"
              next-text="下一页"></page>
    </card>
</template>
<script>
    import API from '../../lib/API_PATH'
    import tagSelect from '../../components/tag-select'
    import mixinList from '../../mixins/list'

    const API_NAME = '文章'

    export default {
        name: 'Article',
        mixins: [mixinList],
        data() {
            return {
                apiUrl: API.ARTICLE,
                search: {
                    title: '',
                    sort: -1,
                    top: null,
                    state: null,
                    tag: ''
                },
                selects: [],
                tag: [],
                table: {
                    header: [
                        {
                            width: 60,
                            type: 'selection'
                        },
                        {
                            type: 'index',
                            width: 60
                        },
                        {
                            title: '名称',
                            key: 'title'
                        },
                        {
                            title: '描述',
                            tooltip: true,
                            key: 'desc'
                        },
                        {
                            title: '栏目',
                            tooltip: true,
                            key: 'tag',
                            render: (h, params) => {
                                const row = params.row
                                let tags = []
                                for (let i of row.tag) {
                                    let t = h('Button', {
                                        props: {
                                            type: 'text',
                                            size: 'small',
                                        },
                                        on: {
                                            click: (e) => {
                                                let tag = this.tag
                                                if (!tag.includes(i._id)) {
                                                    tag.push(i._id)
                                                    this.searchFn()
                                                }
                                            }
                                        }
                                    }, i.name)
                                    tags.push(t)
                                }
                                return h('div', {
                                    style: {
                                        padding: '3px 0'
                                    }
                                }, [
                                    ...tags
                                ])
                            }
                        },
                        {
                            title: '置顶',
                            key: 'top',
                            width: 90,
                            filterMultiple: false,
                            filters: [
                                {
                                    label: '已置顶',
                                    value: 1
                                },
                                {
                                    label: '未置顶',
                                    value: 2
                                }
                            ],
                            filterRemote: (value, row) => {
                                if (value[0] === 1) {
                                    this.search.top = true
                                } else if (value[0] === 2) {
                                    this.search.top = false
                                } else {
                                    this.search.top = null
                                }
                                this.getDataFn()
                            },
                            render: (h, params) => {
                                let color = ''
                                let text = '否'
                                if (params.row.top) {
                                    color = 'red'
                                    text = '已置顶'
                                }
                                return h('span', {
                                    style: {
                                        color
                                    }
                                }, text)
                            }
                        },
                        {
                            title: '状态',
                            key: 'state',
                            width: 90,
                            filterMultiple: false,
                            filters: [
                                {
                                    label: '已上架',
                                    value: 1
                                },
                                {
                                    label: '已下架',
                                    value: 2
                                }
                            ],
                            filterRemote: (value, row) => {
                                if (value[0] === 1) {
                                    this.search.state = '1'
                                } else if (value[0] === 2) {
                                    this.search.state = '2'
                                } else {
                                    this.search.state = null
                                }
                                this.getDataFn()
                            },
                            render: (h, params) => {
                                let color = ''
                                let text = '已上架'
                                if (params.row.state === '1') {
                                    color = '#19be6b'
                                    text = '已上架'
                                }
                                if (params.row.state === '2') {
                                    color = ''
                                    text = '已下架'
                                }
                                return h('span', {
                                    style: {
                                        color
                                    }
                                }, text)
                            }
                        },
                        {
                            title: '建立日期',
                            key: 'createAt',
                            sortable: 'custom',
                            render: (h, params) => {
                                return h('span', this.$utils.dateFormat(params.row.createAt))
                            }
                        },
                        {
                            title: '操作',
                            width: 240,
                            render: (h, params) => {
                                const row = params.row
                                const id = row._id
                                const top = row.top
                                const state = row.state
                                const deleteBtn = h('Button', {
                                    props: {
                                        type: 'error',
                                        size: 'small',
                                        ghost: true
                                    },
                                    on: {
                                        click: () => {
                                            this.$Modal.confirm({
                                                title: '您确定要删除这一项吗？',
                                                content: `<div>文章名称为 <strong style="color: red">${row.title}</strong><div>`,
                                                onOk: () => {
                                                    this.removeDataFn(id)
                                                }
                                            })
                                        }
                                    }
                                }, '删除')
                                const editBtn = h('Button', {
                                    props: {
                                        type: 'info',
                                        size: 'small',
                                        ghost: true,
                                    },
                                    on: {
                                        click: () => {
                                            this.$router.push('/article_ce?type=edit&id=' + id)
                                        }
                                    }
                                }, '修改')
                                const topToggleBtn = h('Button', {
                                    props: {
                                        type: top ? 'warning' : 'primary',
                                        size: 'small',
                                        ghost: true,
                                    },
                                    on: {
                                        click: () => {
                                            this.toggleTop(id)
                                        }
                                    }
                                }, top ? '取消置顶' : '置顶')
                                const stateBtn = h('Button', {
                                    props: {
                                        type: state === '1' ? 'warning' : 'success',
                                        size: 'small',
                                        ghost: true,
                                    },
                                    on: {
                                        click: () => {
                                            let s = '1'
                                            if (state === '1') {
                                                s = '2'
                                            }
                                            this.stateUpdate(id, s)
                                        }
                                    }
                                }, state === '1' ? '下架' : '上架')
                                return h('button-group', [
                                    deleteBtn,
                                    editBtn,
                                    topToggleBtn,
                                    stateBtn,
                                ])
                            }
                        }
                    ],
                    body: [],
                },
            }
        },
        created() {
        },
        mounted() {
        },
        methods: {
            async getDataFn() {
                this.loading = true
                const params = {
                    page: this.page.page,
                    limit: this.page.limit,
                    ...this.search
                }
                params.tag = JSON.stringify(this.tag)
                try {
                    const {data} = await this.$http(API.ARTICLE, {params})
                    this.table.body = data.list
                    this.page.total = data.count
                    this.page.page = parseInt(data.page)
                } catch (e) {
                    console.error(e)
                }
                this.loading = false
            },
            // 删除数据
            async removeDataFn(id) {
                try {
                    const {data} = await this.$http.delete(API.ARTICLE, {params: {id}})
                    this.getDataFn()
                    this.$Message.success(`删除${API_NAME}成功`)
                } catch (e) {
                    console.log(e)
                    this.$utils.errMessage(e, `删除${API_NAME}`)
                }
            },
            // 置顶文章
            async toggleTop(id) {
                try {
                    const {data} = await this.$http.put(API.ARTICLE_TOP, {id})
                    this.getDataFn()
                    this.$Message.success(data.message)
                } catch (e) {
                    console.log(e)
                    this.$utils.errMessage(e, `操作`)
                }
            },
            // 排序
            sortFn(item) {
                console.log(item)
                const order = item.order
                const key = item.key
                if (key === 'createAt') {
                    if (order === 'normal') {
                        this.search.sort = -1
                    } else if (order === 'desc') {
                        this.search.sort = 1
                    } else {
                        this.search.sort = -1
                    }
                }
                this.getDataFn()
            },
            // 文章状态变更
            async stateUpdate(id, state) {
                // ARTICLE_STATE
                try {
                    const {data} = await this.$http.put(API.ARTICLE_STATE, {id, state})
                    this.getDataFn()
                    this.$Message.success(data.message)
                } catch (e) {
                    console.log(e)
                    this.$utils.errMessage(e, `状态变更`)
                }
            },
            selectTableFn(selection) {
                this.selects = selection
            },
            removeSelectsFn() {
                const all = this.selects
                const len = all.length
                let num = 0
                let errTs = []
                let fn = async (item) => {
                    try {
                        const {data} = await this.$http.delete(API.ARTICLE, {params: {id: item._id}})
                    } catch (e) {
                        console.error(e)
                        errTs.push(item.title)
                    }
                    num += 1
                    if (num === len) {
                        this.getDataFn()
                        if (errTs.length > 0) {
                            this.$Message.error(`删除文章 ${item.title} 失败`)
                        } else {
                            this.$Message.success(`批量删除文章成功`)
                        }
                    }
                }
                this.$Modal.confirm({
                    title: '您确定要删除这些文章吗？',
                    onOk: () => {
                        for (let i of all) {
                            fn(i)
                        }
                    }
                })
            }
        },
        components: {
            tagSelect
        }
    }
</script>
